<template>
    <el-card>
        <template #header>
            <p>修改密码</p>
        </template>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="新密码" prop="password">
                <el-input v-model="form.password" type="password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="changePassword">修改密码</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script setup>
import { ref } from 'vue';
import { updateKey } from '@/api/student';
import { ElMessage } from 'element-plus';

const formRef = ref(null);
const form = ref({
    username: 'admin',
    password: '',
});

const rules = {
    password: [
        { required: true, message: '请输入新密码', trigger: 'change' },
        { min: 6, message: '密码不能少于6位', trigger: 'change' },
        { max: 12, message: '密码不能大于12位', trigger: 'change' },
    ],
};

const changePassword = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            updateKey(form.value)
                .then(() => {
                    ElMessage({ type: 'success', message: '修改成功' });
                })
                .catch((error) => {
                    ElMessage({ type: 'error', message: error.message });
                });
        } else {
            ElMessage({ type: 'error', message: '表单填写不完整或不符合要求' });
        }
    });
};
</script>
